$(document).ready(function() {
    let currentPage = 1;
    let pageSize = 10;
    // 存储当前选中的举报ID
    let selectedReportIds = [];
    // 存储当前操作的单个举报ID
    let currentReportId = null;
    // 页面初始化
    function init() {
        getStatics();
        // 初始化页面数据
        initReportList();

        initActionEvents();
    }
    
    // 启动初始化
    init();
    /**
     * 获取筛选参数
     */
    function getFilterParams() {
        return {
            page: currentPage,
            pageSize: pageSize,
            reportStatus: $('#reportStatusFilter').val(),
            reportType: $('#reportTypeFilter').val(),
            sort: $('#sortFilter').val(),
            keyword: $('#keywordSearch').val().trim(),
            submitter: $('#reporterSearch').val().trim(),
            startDate: $('#collectionStartDate').val(),
            endDate: $('#collectionEndDate').val()
        };
    }
    /**
     * 更新已选择数量显示
     */
    function updateSelectedCount() {
        const count = $('.record-checkbox:checked').length;
        $('#SelectedCount').text(`已选择 ${count} 项`);

    }
    /**
     * 渲染分页控件
     * @param {number} total - 总记录数
     * @param {number} currentPage - 当前页码
     * @param {number} pageSize - 每页条数
     */
    function renderPagination(total, currentPage, pageSize) {
        const totalPages = Math.ceil(total / pageSize);
        const paginationContainer = $('#reportPagination'); // 分页容器
        
        // 清空现有分页
        paginationContainer.empty();
        
        // 上一页按钮
        const prevDisabled = currentPage === 1 ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage - 1}" ${prevDisabled}>
                <i class="fa fa-angle-left"></i>
            </button>
        `);
        
        // 页码按钮（最多显示5个页码）
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        // 调整显示范围
        if (endPage - startPage < 4 && totalPages > 5) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
            paginationContainer.append(`
                <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                    ${i}
                </button>
            `);
        }
        
        // 下一页按钮
        const nextDisabled = currentPage === totalPages ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage + 1}" ${nextDisabled}>
                <i class="fa fa-angle-right"></i>
            </button>
        `);
        
        // 更新分页信息
        const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
        const end = Math.min(currentPage * pageSize, total);
        $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
    }
    // 初始化举报列表
    function initReportList() {
        // 显示加载中状态
        $('#reportTableBody').html('<tr><td colspan="9" class="text-center py-4">加载中...</td></tr>');
        
        // 获取筛选参数
        const params = getFilterParams();
        
        // 调用后端接口获取数据
        fetchCollectionList(params)
            .then(result => {
                renderReportTable(result.data.list);
                renderPagination(result.data.total, currentPage, pageSize);
                updateSelectedCount();
                updateBatchButtons();
            })
            .catch(error => {
                // console.error('加载数据失败:', error);
                $('#reportTableBody').html('<tr><td colspan="8" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
            });
    }
    /**
     * 获取举报列表
     * @param {*} params 
     * @returns 
     * */
    async function fetchCollectionList(params) {
        try {
            // 构建查询字符串
            const queryParams = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== undefined && value !== null && value !== '') {
                    queryParams.append(key, value);
                }
            });

            // 发起请求
            const response = await fetch(`/system/GetReportList?${queryParams.toString()}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    // 根据实际需求添加认证信息
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            if (response.status/1 != 200) {
                throw new Error(`请求失败: ${response.statusText}`);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            showToast(error.message || '获取媒体内容列表失败');
        }
    }
    // 渲染举报表格
    function renderReportTable(reports) {
        const tableBody = $('#reportTableBody');
        tableBody.empty();
        
        reports.forEach(report => {
            // 处理状态样式
            let statusClass = '';
            let statusText = '';
            
            switch(report.handle_status) {
                case '1':
                    statusClass = 'bg-warning/10 text-warning';
                    statusText = '待处理';
                    break;
                case '2':
                    statusClass = 'bg-success/10 text-success';
                    statusText = '已处理';
                    break;
                case '3':
                    statusClass = 'bg-neutral-100 text-neutral-500';
                    statusText = '已驳回';
                    break;
            }
            
            // 认领信息
            let claimInfo = '未认领';
            if (report.claimed_by) {
                claimInfo = `
                    <div>
                        <p class="text-sm">审核员ID: ${report.claimed_by}</p>
                        <p class="text-xs text-neutral-500">${report.claimed_time}</p>
                    </div>
                `;
            }
            
            // 操作按钮
            let actionButtons = '';
            if (report.handle_status === '1') {
                // 待处理状态
                actionButtons = `
                    <div class="flex space-x-1">
                        <button class="text-primary hover:text-primary/80 text-sm view-btn" data-id="${report.report_id}" data-content-id="${report.reported_id}" data-content-type="${report.reported_type}">
                            <i class="fa fa-eye mr-1"></i> 查看
                        </button>
                        ${!report.claimed_by ? `
                            <button class="text-primary hover:text-primary/80 text-sm claim-btn" data-id="${report.report_id}">
                                <i class="fa fa-hand-paper-o mr-1"></i> 认领
                            </button>
                        ` : ''}
                        ${report.claimed_by ? `
                            <button class="text-success hover:text-success/80 text-sm process-btn" data-id="${report.report_id}">
                                <i class="fa fa-check mr-1"></i> 处理
                            </button>
                        ` : ''}
                    </div>
                `;
            } else {
                // 已处理或已驳回状态
                actionButtons = `
                    <div class="flex space-x-1">
                        <button class="text-primary hover:text-primary/80 text-sm view-btn" data-id="${report.report_id}" data-content-id="${report.reported_id}" data-content-type="${report.reported_type}">
                            <i class="fa fa-eye mr-1"></i> 查看
                        </button>
                        <!--<button class="text-neutral-500 hover:text-neutral-700 text-sm detail-btn" data-id="${report.report_id}">
                            <i class="fa fa-history mr-1"></i> 详情
                        </button>-->
                    </div>
                `;
            }
            
            const row = `
                <tr>
                    <td class="px-5 py-4 whitespace-nowrap">
                        <input type="checkbox" class="report-checkbox rounded border-neutral-300 text-primary focus:ring-primary" data-id="${report.report_id}" ${report.handle_status !== '1' ? 'disabled' : ''}>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${report.report_id}</td>
                    <td class="px-5 py-4 whitespace-nowrap">
                        <div>
                            <p class="text-sm">ID: ${report.reported_id}</p>
                            <p class="text-xs text-neutral-500">类型: ${report.reported_type}</p>
                        </div>
                    </td>
                    <td class="px-5 py-4 max-w-xs">
                        <p class="text-sm line-clamp-2">${report.report_reason}</p>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${report.report_user_id}</td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${report.report_time}</td>
                    <td class="px-5 py-4 whitespace-nowrap">
                        <span class="px-2 py-1 text-xs rounded-full ${statusClass}">
                            ${statusText}
                        </span>
                        <span class="px-2 py-1 text-xs rounded-full">
                            ${report.remark?report.remark:''}
                        </span>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap">${claimInfo}</td>
                    <td class="px-5 py-4 whitespace-nowrap">${actionButtons}</td>
                </tr>
            `;
            
            tableBody.append(row);
        });
        
        // 绑定表格按钮事件
        bindTableEvents();
    }
    
    // 绑定表格按钮事件
    function bindTableEvents() {
        // 单行选择
        $('.report-checkbox').change(function() {
            const reportId = $(this).data('id');
            
            if ($(this).is(':checked')) {
                selectedReportIds.push(reportId);
            } else {
                selectedReportIds = selectedReportIds.filter(id => id !== reportId);
            }
            
            updateBatchButtons();
        });
        
        // 全选
        $('#selectAll').change(function() {
            const isChecked = $(this).is(':checked');
            const checkboxes = $('.report-checkbox:enabled');
            
            if (isChecked) {
                selectedReportIds = [];
                checkboxes.each(function() {
                    $(this).prop('checked', true);
                    selectedReportIds.push($(this).data('id'));
                });
            } else {
                checkboxes.prop('checked', false);
                selectedReportIds = [];
            }
            
            updateBatchButtons();
        });
        
        // 查看被举报内容
        $('.view-btn').click(function() {
            const reportId = $(this).data('id');
            const contentId = $(this).data('content-id');
            const contentType = $(this).data('content-type');
            
            viewReportedContent(reportId, contentId, contentType);
        });
        
        // 认领举报
        $('.claim-btn').click(function() {
            currentReportId = $(this).data('id');
            showClaimModal(false);
        });
        
        // 处理举报
        $('.process-btn').click(function() {
            currentReportId = $(this).data('id');
            showProcessModal(false);
        });
        
        // 查看处理详情
        $('.detail-btn').click(function() {
            const reportId = $(this).data('id');
            showReportDetail(reportId);
        });
    }
    
    // 更新批量操作按钮状态
    function updateBatchButtons() {
        const count = selectedReportIds.length;
        $('#selectedCount').text(`已选择 ${count} 项`);
        
        if (count > 0) {
            $('#batchClaimBtn').prop('disabled', false);
            $('#batchProcessBtn').prop('disabled', false);
            $('#batchRejectBtn').prop('disabled', false);
        } else {
            $('#batchClaimBtn').prop('disabled', true);
            $('#batchProcessBtn').prop('disabled', true);
            $('#batchRejectBtn').prop('disabled', true);
        }
    }
    
    // 显示认领模态框
    function showClaimModal(isBatch) {
        if (isBatch) {
            $('#batchClaimInfo').removeClass('hidden');
            $('#batchClaimCount').text(`将批量认领 ${selectedReportIds.length} 条举报`);
        } else {
            $('#batchClaimInfo').addClass('hidden');
            $('#claimModalMessage').text(`您确定要认领举报 ${currentReportId} 的处理任务吗？认领后其他审核员将无法操作。`);
        }
        
        $('#claimModal').removeClass('hidden').addClass('flex');
    }
    
    // 显示处理模态框
    function showProcessModal(isBatch) {
        if (isBatch) {
            $('#batchProcessInfo').removeClass('hidden');
            $('#batchProcessCount').text(`将批量处理 ${selectedReportIds.length} 条举报`);
        } else {
            $('#batchProcessInfo').addClass('hidden');
            $('#processModalMessage').text(`请选择对举报 ${currentReportId} 的处理方式`);
        }
        
        $('#processModal').removeClass('hidden').addClass('flex');
    }
    
    // 查看被举报内容
    function viewReportedContent(reportId, contentId, contentType) {
        // 模拟加载内容 - 实际应从API获取
        $('#previewContentId').text(contentId);
        $('#previewContentType').text(contentType);
        
        let contentHtml = '';
        switch(contentType) {
            case '媒体':
                contentHtml = `
                    <div class="flex justify-center my-4">
                        <img src="/i/sample-media.jpg" alt="媒体内容预览" class="max-w-full max-h-96 object-contain rounded-lg">
                    </div>
                    <p class="text-sm text-neutral-600">这是媒体内容的预览，实际应用中会加载真实内容。</p>
                `;
                break;
            case '言论':
                contentHtml = `
                    <div class="bg-neutral-50 p-4 rounded-lg my-4">
                        <p class="text-sm">这是一条用户发表的言论内容，可能包含被举报的敏感信息。实际应用中会显示真实的用户言论内容。</p>
                    </div>
                `;
                break;
            case '合集':
                contentHtml = `
                    <div class="grid grid-cols-3 gap-2 my-4">
                        <img src="/i/sample-collection-1.jpg" alt="合集内容1" class="w-full h-24 object-cover rounded">
                        <img src="/i/sample-collection-2.jpg" alt="合集内容2" class="w-full h-24 object-cover rounded">
                        <img src="/i/sample-collection-3.jpg" alt="合集内容3" class="w-full h-24 object-cover rounded">
                    </div>
                    <p class="text-sm text-neutral-600">这是合集内容的预览，包含多个媒体资源。</p>
                `;
                break;
            case '认证':
                contentHtml = `
                    <div class="space-y-3 my-4">
                        <div class="flex justify-between">
                            <span class="text-sm text-neutral-500">认证类型:</span>
                            <span class="text-sm">个人认证</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-sm text-neutral-500">真实姓名:</span>
                            <span class="text-sm">张三</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-sm text-neutral-500">证件类型:</span>
                            <span class="text-sm">身份证</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-sm text-neutral-500">证件号码:</span>
                            <span class="text-sm">110********1234</span>
                        </div>
                    </div>
                `;
                break;
        }
        
        $('#previewContentBody').html(contentHtml);
        $('#contentPreviewModal').removeClass('hidden').addClass('flex');
    }
    
    // 显示举报处理详情
    function showReportDetail(reportId) {
        // 实际应用中应从API获取详情数据并显示
        showToast(`举报 ${reportId} 的处理详情`, 'info');
    }

    // 初始化操作按钮事件
    function initActionEvents() {

        // 分页按钮点击事件
        $(document).on('click', '.pagination-btn', function() {
            const page = parseInt($(this).data('page'));
            if (!isNaN(page) && page !== currentPage) {
                currentPage = page;
                initReportList()
            }
        });
    }
    
    // 筛选按钮点击事件
    $('#filterBtn').click(function() {        
        // 这里可以根据筛选条件重新加载表格数据
        initReportList();
    });
    
    // 重置按钮点击事件
    $('#resetBtn').click(function() {
        $('#reportStatusFilter').val('');
        $('#reportTypeFilter').val('');
        $('#keywordSearch').val('');
        $('#reporterSearch').val('');
        $('#startDate').val('');
        $('#endDate').val('');
        $('#sortFilter').val('0');
        
        // 重置表格数据
        initReportList();
        selectedReportIds = [];
        updateBatchButtons();
        $('#selectAll').prop('checked', false);
    });
    
    // 批量认领按钮点击事件
    $('#batchClaimBtn').click(function() {
        showClaimModal(true);
    });
    
    // 批量处理按钮点击事件
    $('#batchProcessBtn').click(function() {
        showProcessModal(true);
    });
    
    // 批量驳回按钮点击事件
    $('#batchRejectBtn').click(function() {
        const checkedItems = $('.report-checkbox:checked');
        const ids = Array.from(checkedItems).map(item => $(item).data('id'));
        
        if (ids.length === 0) {
            showToast('请选择要认领的记录', 'warning');
            return;
        }

        batchReject(ids)
                .then(() => {
                    initReportList(); // 重新加载列表
                    showToast('批量处理成功', 'success');
                    updateSelectedCount();
                    updateBatchButtons();
                    selectedReportIds = [];
                })
                .catch(error => {
                    showToast('批量处理失败，请重试', 'error');
                });
    });
    /**
     * 批量拒绝方法
     */
    async function batchReject(ids){
        try {
            let requestData = { ids: ids };
            let url = '/system/BatchProcessReport';
            const processType = $('input[name="processType"]:checked').val();
            const remark = $('#processRemark').val();
            const violationTypeSelect = $('#violationTypeSelect').val();
            requestData.violationType = violationTypeSelect;
            requestData.processType = 'reject';
            requestData.remark = remark; 
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result;
        }catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    /**
     * 批量操作通用方法
     * @param {Array} ids - 内容ID数组
     * @param {string} action - 操作类型(approve/reject)
     * @returns {Promise}
     */
    async function batchOperate(ids, action) {
        try {
            let url = '';
            let requestData = { ids: ids };

            switch(action) {
                case 'approve':
                    url = '/system/BatchProcessReport';
                    const processType = $('input[name="processType"]:checked').val();
                    const remark = $('#processRemark').val();
                    const violationTypeSelect = $('#violationTypeSelect').val();
                    requestData.violationType = violationTypeSelect;
                    requestData.processType = processType;
                    requestData.remark = remark;    
                    break;
                case 'claim':  // 添加认领操作支持
                    url = '/system/BatchClaimReport';  // 假设的后端API地址
                    requestData.remark = $('#claimRemark').val() || '';  // 可选备注
                    break;
                default:
                    throw new Error('不支持的操作类型');
            }

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    // 确认认领按钮点击事件
    $('#confirmClaimBtn').click(function() {
        const checkedItems = $('.report-checkbox:checked');
        const ids = Array.from(checkedItems).map(item => $(item).data('id'));
        
        if (ids.length === 0) {
            showToast('请选择要认领的记录', 'warning');
            return;
        }

        batchOperate(ids, 'claim')
                .then(() => {
                    initReportList(); // 重新加载列表
                    showToast('批量认领成功', 'success');
                    // 关闭模态框
                    $('#claimModal').removeClass('flex').addClass('hidden');
                    updateSelectedCount();
                    updateBatchButtons();
                    selectedReportIds = [];
                })
                .catch(error => {
                    showToast('批量认领失败，请重试', 'error');
                });

    });
    
    // 取消认领按钮点击事件
    $('#cancelClaimBtn').click(function() {
        $('#claimModal').removeClass('flex').addClass('hidden');
        currentReportId = null;
    });
    
    // 确认处理按钮点击事件
    $('#confirmProcessBtn').click(function() {
        const checkedItems = $('.report-checkbox:checked');
        const ids = Array.from(checkedItems).map(item => $(item).data('id'));
        
        if (ids.length === 0) {
            if(currentReportId){
                ids.push(currentReportId);
            }else{
                showToast('请选择要处理的记录', 'warning');
                return;
            }
        }

        batchOperate(ids, 'approve')
                .then(() => {
                    initReportList(); // 重新加载列表
                    showToast('批量处理成功', 'success');
                    // 关闭模态框
                    $('#claimModal').removeClass('flex').addClass('hidden');
                    updateSelectedCount();
                    updateBatchButtons();
                    selectedReportIds = [];
                    $('#processModal').removeClass('flex').addClass('hidden');
                })
                .catch(error => {
                    showToast('批量处理失败，请重试', 'error');
                });
        

    });
    
    // 取消处理按钮点击事件
    $('#cancelProcessBtn').click(function() {
        $('#processModal').removeClass('flex').addClass('hidden');
        currentReportId = null;
    });
    
    // 关闭内容预览模态框
    $('#closePreviewModal').click(function() {
        $('#contentPreviewModal').removeClass('flex').addClass('hidden');
    });
    
    // 处理方式选择变化事件
    $('input[name="processType"]').change(function() {
        const processType = $(this).val();
        if (processType === 'confirm') {
            $('#violationTypeContainer').removeClass('hidden');
        } else {
            $('#violationTypeContainer').addClass('hidden');
        }
    });

    

    /**
     * 获取统计数据
     */
    async function getStatics() {
        try {
            const response = await fetch('/system/GetReportStats'); // 假设接口地址
            const result = await response.json();
            
            if (result.status === 0) {
                const { pending, processed, rejected } = result.data;
                
                // 更新待处理举报数据
                $('#pendingReportCount').text(pending.count);
                // 修正选择器：通过父容器定位百分比元素
                const pendingRateEl = $('#pendingReportCount')
                    .closest('div.flex.items-start.justify-between')
                    .siblings('div.flex.items-center.text-sm')
                    .find('span:first');
                pendingRateEl.html(`<i class="fa fa-arrow-${pending.growthRate >= 0 ? 'up' : 'down'} mr-1"></i> ${Math.abs(pending.growthRate).toFixed(1)}%`);
                pendingRateEl.toggleClass('text-danger', pending.growthRate >= 0);
                pendingRateEl.toggleClass('text-success', pending.growthRate < 0);
                
                // 更新已处理举报数据
                $('#processedReportCount').text(processed.count);
                const processedRateEl = $('#processedReportCount')
                    .closest('div.flex.items-start.justify-between')
                    .siblings('div.flex.items-center.text-sm')
                    .find('span:first');
                processedRateEl.html(`<i class="fa fa-arrow-${processed.growthRate >= 0 ? 'up' : 'down'} mr-1"></i> ${Math.abs(processed.growthRate).toFixed(1)}%`);
                processedRateEl.toggleClass('text-success', processed.growthRate >= 0);
                processedRateEl.toggleClass('text-danger', processed.growthRate < 0);
                
                // 更新已驳回举报数据
                $('#rejectedReportCount').text(rejected.count);
                const rejectedRateEl = $('#rejectedReportCount')
                    .closest('div.flex.items-start.justify-between')
                    .siblings('div.flex.items-center.text-sm')
                    .find('span:first');
                rejectedRateEl.html(`<i class="fa fa-arrow-${rejected.growthRate >= 0 ? 'up' : 'down'} mr-1"></i> ${Math.abs(rejected.growthRate).toFixed(1)}%`);
                rejectedRateEl.toggleClass('text-danger', rejected.growthRate >= 0);
                rejectedRateEl.toggleClass('text-success', rejected.growthRate < 0);
            } else {
                console.error('获取统计数据失败:', result.msg);
                showToast('获取统计数据失败', 'error');
            }
        } catch (error) {
            console.error('获取统计数据出错:', error);
            showToast('获取统计数据出错', 'error');
        }
    }
});